package com.study.javaBasic.multithreading;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class FutureTaskDemo {
    static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setPoolName("thread-start-runner-%d").build();
    static ExecutorService taskExe = new ThreadPoolExecutor(10, 20, 800L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100), namedThreadFactory);
    static int count = 0;

    public static void main(String[] args) {

        //任务列表
        List<FutureTask<Integer>> taskList = new ArrayList<FutureTask<Integer>>();
        for (int i = 0; i < 100; i++) {
            //创建100个任务放入【任务列表】
            FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return 1;
                }
            });
            //执行的结果装回原来的FutureTask中,后续直接遍历集合taskList来获取结果即可
            taskList.add(futureTask);
            taskExe.submit(futureTask);
        }
        //获取结果
        try {
            for (FutureTask<Integer> futureTask : taskList) {
                count += futureTask.get();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //关闭线程池
        taskExe.shutdown();
        //打印: 100
        System.out.println(count);
    }
}
